package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    IPaymentInfoService paymentInfoService;


    @Override
    public String submitAlipay(String orderNo) {

        //1.先保存支付信息
        PaymentInfo paymentInfo = paymentInfoService.savePayment(orderNo);

        //2.调用支付接口：alipay.trade.wap.pay(手机网站支付接口2.0)

        try {
            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();

            // 同步回调
            // return_payment_url=http://sph-payment.atguigu.cn/alipay/callback/return
            alipayRequest.setReturnUrl(AlipayConfig.return_payment_url); //通知前端
            // 异步回调
            alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);// 通知后端
            // 参数
            // 声明一个map 集合
            HashMap<String, Object> map = new HashMap<>();
            map.put("out_trade_no",paymentInfo.getOrderNo()); //商户订单号
            map.put("product_code","QUICK_WAP_WAY"); //签约的支付产品类型
            map.put("total_amount",paymentInfo.getAmount()); //由于调用沙箱版支付接口，测试环境。余额100万，可以随便花
            //map.put("total_amount","0.01"); //如果调用正式支付宝，可以模拟支付1分钱。
            map.put("subject",paymentInfo.getContent());
            map.put("time_expire","2025-08-16 12:00:00"); //设置订单绝对超时时间

            alipayRequest.setBizContent(JSON.toJSONString(map));

            AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest, "post");
            String h5Form = response.getBody();
            return h5Form;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new ServiceException("调用支付接口失败");
        }
    }
}
